/*
 *  ClientQueue.c
 *  ClientDispatch
 *
 *  Created by Andrey on 13/10/2008.
 *  Copyright 2008 ИУ7-2003. All rights reserved.
 *
 */
#include <stdlib.h>
#include <pthread.h>

#include "ClientQueue.h"

TAILQ_HEAD(CDClientQueue, _CDClientInfo) _cdClientQueue = TAILQ_HEAD_INITIALIZER(_cdClientQueue);
pthread_mutex_t _cdClientQueueMutex;

void InitClientQueue()
{
	pthread_mutex_init(&_cdClientQueueMutex, NULL);
	TAILQ_INIT(&_cdClientQueue);
}

void AddClientToQueue(CDClientInfoPtr clientInfo)
{
	pthread_mutex_lock(&_cdClientQueueMutex);
	if (clientInfo != NULL)
		TAILQ_INSERT_TAIL(&_cdClientQueue, clientInfo, clientQueueEntries);
	pthread_mutex_unlock(&_cdClientQueueMutex);
}

CDClientInfoPtr GetFirstClientInQueue()
{
	pthread_mutex_lock(&_cdClientQueueMutex);
	CDClientInfoPtr firstClientInQueue = TAILQ_FIRST(&_cdClientQueue);
	if (firstClientInQueue != NULL)
		TAILQ_REMOVE(&_cdClientQueue, firstClientInQueue, clientQueueEntries);
	pthread_mutex_unlock(&_cdClientQueueMutex);
	
	return firstClientInQueue;
}

void PurgeClientQueue()
{
	CDClientInfoPtr queueEntry = (CDClientInfoPtr)TAILQ_FIRST(&_cdClientQueue);
	CDClientInfoPtr nextQueueEntry;
	
	pthread_mutex_lock(&_cdClientQueueMutex);
	while (queueEntry != NULL) 
	{
		nextQueueEntry = (CDClientInfoPtr)TAILQ_NEXT(queueEntry, clientQueueEntries);
		//free(queueEntry);
		queueEntry = nextQueueEntry;
	}
	pthread_mutex_unlock(&_cdClientQueueMutex);
	
	pthread_mutex_destroy(&_cdClientQueueMutex);
}